// 主要容器
import React, { Component } from "react";
import Header from "../Components/Header";
import { Dropdown, Layout, Menu, message, Modal } from "antd";
import {
  BookTwoTone,
  CloudDownloadOutlined,
  FolderAddTwoTone,
  FolderOpenOutlined,
  FolderOpenTwoTone,
  RestTwoTone,
} from "@ant-design/icons";
import ButtonPri from "../Components/ButtonPri";
import Search from "../Components/Search";
import Editor from "../Components/Editor";
// import RightClick from "../Components/RightClick";
import axios from "../Api/api";
import { withRouter } from "react-router-dom";
import { serverMainPath } from "../Api/BaseUrl";
import "../Style/mainstyle.scss";

const { SubMenu } = Menu;
const { Content, Sider } = Layout;

let valarr = [];

class Main extends Component {
  state = {
    wjjname: [],
    bjname: [],
    rightTreeVisible: false,
    bjvisible: false,
    notevalueInput: "",
    noteListArr: ["a", "b", "c"],
    userInfo: {},
    folderDataList: [],
    notebookInfo: [],
    bookContent: "",
    hasnotebook: false,
    mouseDownContent: {},
    user_folder_id: 3,
    clickFolderData: {},
    stardid: null,
    fileList: [],
    fileIsClicked: "",
    reNameFolderVisible: false,
    reNameValueInput: "",
    fileClickid: 0,
    deleteFolderList: [],
    editorVisible: true,
    NoteContent: "",
    _notebookid: 1,
  };

  constructor(props) {
    super(props);
    this.getFolderData = this.getFolderData.bind(this);
    this.folderdata = this.folderdata.bind(this);
    this.sub1 = this.sub1.bind(this);
    // this.folderItem = this.folderItem.bind(this);
    this.overlayAllFun = this.overlayAllFun.bind(this);
    this.hasNoteBooks = this.hasNoteBooks.bind(this);
    this.delFolder = this.delFolder.bind(this);
    this.addNotebook = this.addNotebook.bind(this);
    this.reName = this.reName.bind(this);
    this.getUploadFilesList = this.getUploadFilesList.bind(this);
    this.doDownLoadFile = this.doDownLoadFile.bind(this);
    this.delFiles = this.delFiles.bind(this);
    this.download = this.download.bind(this);
    this.deleteFolderListData = this.deleteFolderListData.bind(this);
    this.isEditorShow = this.isEditorShow.bind(this);
    // this.state.notebookInfo = store.getState();
  }

  //组件挂载后
  componentDidMount() {
    //Done 路由传参
    this.state.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    // console.log(this.state.userInfo)

    if (this.state.userInfo) {
      this.getFolderData();
      this.getUploadFilesList();
      this.deleteFolderListData();
      // this.notebookContent({key:0});
    }
  }

  //promise
  // let promise = new Promise((res, rej) => {
  //     console.log(this.state.wjjname.length, "[][][]")
  //     res("done");
  //     console.log("222")
  // }).then((res) => {
  //         // res("123123")
  //     console.log(res);
  //
  // }).then((res) => {
  //     console.log(res);
  //     this.folderdata({key: 0});
  // }).catch((error) => {
  //     console.log(error)
  // })

  //获取上传文件目录
  getUploadFilesList() {
    axios(
      serverMainPath.getUploadFilesList + this.state.userInfo.username
    ).then((res) => {
      if (res.data.length < 0) return;

      // console.log(res.data);
      this.state.fileList = res.data;
    });
  }

  // TODO:这是啥？？
  // Done!!!!!!!!!
  folderItem(item) {
    // console.log(item);
    this.setState({
      mouseDownContent: item,
    });
  }

  //获取文件夹的数据
  getFolderData() {
    // console.log(this.state.userInfo.id)
    axios
      .get(serverMainPath.userInfo + "/?id=" + this.state.userInfo.id)
      .then((res) => {
        valarr = res;
        this.setState({
          wjjname: valarr,
        });
      })
      .then(() => {
        this.folderdata({ key: 0, keyPath: [0, "sub1"] });
      });
  }

  overlayAllFun(key) {
    let funId = Number(key.key);
    let folder = this.state.mouseDownContent;
    if (funId === 1) {
      //添加笔记
      this.addNotebook(folder);
    } else if (funId === 2) {
      //重命名
      this.reName(folder);
    } else if (funId === 4) {
      //删除文件夹
      this.delFolder(folder);
    }
  }

  addNotebook(folder) {
    // console.log(folder);
    this.setState({
      clickFolderData: folder,
      bjvisible: true,
    });
    // if(this.state.notevalueInput !== ''){
    //     this.notehandleOk(folder)
    // }
  }

  notehandleOk() {
    let val = this.state.notevalueInput;
    let folder_data = this.state.clickFolderData;
    let day_now = new Date();
    day_now.setTime(day_now.getTime());
    let today =
      day_now.getFullYear() +
      "-" +
      (day_now.getMonth() + 1) +
      "-" +
      day_now.getDate();
    if (val !== "" && val.length < 20) {
      val = {
        folderid: folder_data.id,
        time: today,
        notename: val,
        username: this.state.userInfo.username,
      };
      axios
        .get(
          serverMainPath.addNotebook +
            val.folderid +
            "/" +
            val.time +
            "/" +
            val.notename +
            "/" +
            val.username
        )
        .then((res) => {
          if (res.code === 200) {
            let bjvalarr = this.state.notebookInfo;
            bjvalarr.push(val);
            message.success("创建笔记成功", 2, onclose);
            this.setState({
              bjvisible: false,
              notebookInfo: bjvalarr,
              notevalueInput: "",
              hasnotebook: false,
            });
          } else if (res.code === 406) {
            message.error("笔记名重复，请重新输入", 2, onclose);
          } else {
            message.error("创建笔记失败", 2, onclose);
          }
        });
    } else {
      message.error("名称不能为空,或者输入的名称不能超过20个字符", 3, onclose);
      this.setState({
        notevalueInput: "",
        bjvisible: true,
      });
    }
  }

  reName() {
    // console.log("dd")
    this.setState({
      reNameFolderVisible: true,
    });
  }

  delFolder(folder) {
    // console.log(folder);
    let afterDeleteArr = this.state.wjjname.filter((item) => {
      return item.foldername !== folder.foldername;
    });
    valarr = valarr.filter((item) => {
      return item.foldername !== folder.foldername;
    });
    axios.get(serverMainPath.deleteFolder + folder.id).then((res) => {
      if (res.code === 200) {
        this.setState({
          wjjname: afterDeleteArr,
        });

        message.success("删除成功", 2);
      } else {
        message.error("删除失败", 2);
      }
    });
  }

  //获取文件夹的内容
  folderdata(item) {
    if (item.keyPath[1] === "sub1") {
      this.sub1(item);
    }
  }

  sub1(item) {
    if (this.state.wjjname.length === 0) {
      this.setState({
        hasnotebook: true,
      });
      return;
    }

    let folder_id = this.state.wjjname.map((e, index) => {
      if (Number(item.key) === index) {
        return e;
      }
    });
    const unique = (array) => {
      let arr = [];
      for (let i = 0; i < array.length; i++) {
        if (array[i] !== undefined) {
          arr.push(array[i]);
        }
      }
      return arr;
    };

    // folder_id.splice(folder_id.findIndex((item) => {
    //     console.log(item)
    // }), 1);
    folder_id = unique(folder_id);
    console.log(folder_id);

    axios
      .get(
        serverMainPath.notebook +
          "?folderid=" +
          folder_id[0].id +
          "&?username=" +
          this.state.userInfo.username
      )
      .then((res) => {
        // console.log(res.data, "book")
        if (res.data.length > 0) {
          this.setState({
            notebookInfo: res.data,
            bookContent: res.data[0].content,
            hasnotebook: false,
          });
        }
        if (res.data.length === 0) {
          this.setState({
            notebookInfo: res.data,
            hasnotebook: true,
          });
        }

        // this.state.notebookInfo=;
        // console.log(this.state.notebookInfo)
      });
  }

  /*
   * 笔记取消
   *
   */
  noteHandleCancel() {
    message.info("取消创建笔记", 1);
    this.setState({
      bjvisible: false,
    });
  }

  //获取笔记的内容
  notebookContent(key) {
    let _key = key.key;

    let content = this.state.notebookInfo[_key];
    let bookId = this.state.notebookInfo[_key].bookid;

    this.setState({
      bookContent: content.content,
      _notebookid: bookId,
    });

    setTimeout(() => {
      this.setState({ editorVisible: true });
    }, 500);
  }
  getNoteBookContent(html) {
    // console.log(this.state.notebookInfo)
    this.setState({
      NoteContent: html,
    });
  }
  isEditorShow() {
    if (this.state.editorVisible === true) {
      if (this.state.bookContent !== null) {
        return (
          <Editor
            bookContent={this.state.bookContent}
            toGetContent={this.getNoteBookContent.bind(this)}
          />
        );
      }
    }
  }

  hasNoteBooks() {
    if (this.state.hasnotebook === true) {
      return (
        <div
          style={{
            fontSize: 24 + "px",
            fontWeight: "bold",
            textAlign: "center",
            position: "absolute",
            top: 100 + "px",
            left: 40 + "px",
          }}
        >
          <p>文件夹没有笔记</p>
        </div>
      );
    } else if (this.state.hasnotebook === "被删除") {
      return (
        <div
          style={{
            fontSize: 24 + "px",
            fontWeight: "bold",
            textAlign: "center",
            marginTop: 100 + "px",
          }}
        >
          <p>此文件夹不存在</p>
        </div>
      );
    }
  }

  //添加文件夹
  handleFromModel(val) {
    if (val !== "" && val.length < 20) {
      let random = Math.floor(Math.random() * 100);
      val = {
        id: random,
        foldername: val,
        user_id: this.state.userInfo.id,
      };
      axios
        .get(
          serverMainPath.addFolder +
            val.id +
            "/" +
            val.foldername +
            "/" +
            val.user_id
        )
        .then((res) => {
          if (res.code === 200) {
            valarr.push(val);
            message.success("创建文件夹成功", 2);
            this.setState({
              wjjname: valarr,
            });
            // console.log(valarr, this.state.wjjname);
          } else if (res.code === 406) {
            message.error("文件夹名重复，请重新输入", 2);
          } else {
            message.error("创建文件夹失败", 2);
          }
        });
    } else {
      message.error("名称不能为空,或者输入的名称不能超过20个字符", 3);
    }
  }

  filesAllFunc(key) {
    if (key.key === "1") {
      this.doDownLoadFile();
    } else if (key.key === "2") {
      this.delFiles();
    }
  }

  handleClickFileDownLoad(item) {
    this.setState({
      fileClickid: item.id,
      fileIsClicked: item.filename,
    });
    // console.log(this.state.fileIsClicked)
  }

  doDownLoadFile() {
    axios(serverMainPath.downloadFiles + this.state.fileIsClicked).then(
      (res) => {
        // if(this.sa){}
        window.location.href =
          "http://106.52.23.236:7003/public/file/" + this.state.fileIsClicked;
      }
    );
  }

  reNameHandleOk() {
    // console.log(this.state.mouseDownContent)
    let folder_id = this.state.mouseDownContent.id;
    axios
      .get(
        serverMainPath.updateFolderName +
          this.state.reNameValueInput +
          "/" +
          folder_id
      )
      .then((res) => {
        if (res.code === 200) {
          message.success("修改成功", 2);

          let arrForFolder = this.state.wjjname;
          arrForFolder.forEach((item) => {
            if (item.id === folder_id) {
              item.foldername = this.state.reNameValueInput;
            }
          });
          this.setState({
            wjjname: arrForFolder,
          });
        } else {
          message.error("修改失败", 2);
        }
      });
    this.setState({
      reNameFolderVisible: false,
    });
  }

  reNameHandleCancel() {
    this.setState({
      reNameFolderVisible: false,
    });
  }

  download(blobUrl) {
    const a = document.createElement("a");
    a.style.display = "none";
    a.download = "导出的文件名";
    a.href = blobUrl;
    a.click();
    document.body.removeChild(a);
  }

  delFiles() {
    let fileArr = this.state.fileList;
    fileArr.forEach((item, index) => {
      if (item.id === this.state.fileClickid) {
        fileArr.splice(index, 1);
      }
    });
    this.setState({
      fileList: fileArr,
    });
    axios
      .get(
        serverMainPath.deleteFile +
          this.state.fileClickid +
          "/" +
          this.state.fileIsClicked
      )
      .then((res) => {
        if (res.code === 200) {
          message.success("删除成功", 2);
          this.deleteFolderListData();
        } else {
          message.error("删除失败", 2);
        }
      });
  }

  deleteFolderListData() {
    axios.get(serverMainPath.getDeleteFolders).then((res) => {
      // console.log(res.data)
      if (res.data.length < 0) return;
      this.setState({
        deleteFolderList: res.data,
      });
    });
  }

  searchClickEvent(item) {
    console.log("click", item);
    let content = item.content;
    this.setState({
      bookContent: content,
    });
  }
  render() {
    const maintain = {
      height: "100%",
    };
    const RightClickMenuSub1 = (
      <Menu onClick={this.overlayAllFun.bind(this)}>
        <Menu.Item key="1">新建笔记</Menu.Item>
        <Menu.Item key="2">重命名</Menu.Item>
        {/* <Menu.Item key="3">阅读密码</Menu.Item> */}
        <Menu.Item danger key="4">
          删除
        </Menu.Item>
      </Menu>
    );

    const RightClickMenuSub2 = (
      <Menu onClick={this.filesAllFunc.bind(this)}>
        <Menu.Item key="1">下载</Menu.Item>
        <Menu.Item danger key="2">
          删除
        </Menu.Item>
      </Menu>
    );

    return (
      <Layout style={maintain}>
        <Header
          userInfo={this.state.userInfo}
          bookContent={this.state.NoteContent}
          bookid={this.state._notebookid}
        />
        <Layout>
          <Sider
            width={230}
            height={100 + "%"}
            className="site-layout-background"
          >
            <ButtonPri
              btntext="新文档"
              handlewjjName={this.handleFromModel.bind(this)}
              handlebjName={this.handleFromModel.bind(this)}
            ></ButtonPri>
            <Menu
              mode="inline"
              defaultSelectedKeys={["0"]}
              defaultOpenKeys={["sub1"]}
              style={{
                height: "calc(100% - 40px)",
                borderRight: 0,
                overflow: "scroll",
              }}
              onClick={this.folderdata}
              className="srollStyle"
            >
              <SubMenu
                key="sub1"
                icon={<FolderAddTwoTone />}
                title="我的文件夹"
              >
                {this.state.wjjname.map((item, index) => {
                  // this.state.folderDataList.push(item);
                  // return <Menu.Item key={index}>{item}</Menu.Item>
                  return (
                    <Menu.Item
                      key={index}
                      onClick={this.folderItem.bind(this, item)}
                    >
                      <Dropdown
                        arrow={true}
                        overlay={RightClickMenuSub1}
                        trigger={["contextMenu"]}
                      >
                        <div>
                          <span className="icons-list">
                            <FolderOpenOutlined />
                          </span>
                          <div key={index} style={{ display: "inline" }}>
                            {item.foldername}
                          </div>
                        </div>
                      </Dropdown>
                    </Menu.Item>
                  );
                })}

                {/*<Menu.Item key="1">{this.state.wjjname}</Menu.Item>*/}
              </SubMenu>
              <SubMenu key="sub2" icon={<FolderOpenTwoTone />} title="文件">
                {this.state.fileList.map((item, index) => {
                  return (
                    <Menu.Item key={index + item}>
                      <Dropdown
                        arrow={true}
                        overlay={RightClickMenuSub2}
                        trigger={["contextMenu"]}
                      >
                        <div
                          onClick={this.handleClickFileDownLoad.bind(
                            this,
                            item
                          )}
                        >
                          <span className="icons-list">
                            <CloudDownloadOutlined />
                          </span>
                          <div key={index} style={{ display: "inline" }}>
                            {item.filename}
                          </div>
                        </div>
                      </Dropdown>
                    </Menu.Item>
                  );
                })}
              </SubMenu>
              <SubMenu key="sub3" icon={<RestTwoTone />} title="回收站">
                {this.state.deleteFolderList.map((item, index) => {
                  return (
                    <Menu.Item key={index + "item"}>
                      {item.foldername}
                    </Menu.Item>
                  );
                })}
                {/*<Menu.Item key="12">option12</Menu.Item>*/}
              </SubMenu>
            </Menu>
          </Sider>
          <Layout style={{ padding: "0" }}>
            <Content
              className="site-layout-background"
              style={{
                padding: 0,
                margin: 0,
                minHeight: 280,
                height: 100 + "%",
                display: "flex",
                justifyContent: "spaceAround",
              }}
            >
              <Sider
                width={250}
                style={{
                  height: 100 + "%",
                  marginRight: 10 + "px",
                  backgroundColor: "rgb(239,242,245)",
                  borderLeft: "1px solid #ccc",
                  borderRight: "1px solid #ccc",
                }}
              >
                {this.hasNoteBooks()}
                <Search clickEvent={this.searchClickEvent.bind(this)} />
                <Menu>
                  {this.state.notebookInfo.map((item, index) => {
                    // return <Menu.Item key={index}>{item}</Menu.Item>
                    return (
                      <Menu.Item
                        key={index}
                        style={{ height: 70 + "px", width: 100 + "%" }}
                        onClick={this.notebookContent.bind(this)}
                      >
                        <div style={{}}>
                          <span className="icons-list">
                            <BookTwoTone
                              style={{ width: 40 + "px", height: 40 + "px" }}
                            />
                          </span>

                          <div
                            key={index}
                            style={{
                              display: "inline",
                              fontSize: 24 + "px",
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                            }}
                          >
                            {item.notename}
                          </div>
                          <div
                            className="noteContent"
                            style={{
                              position: "relative",
                              bottom: 25 + "px",
                              left: 20 + "px",
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                            }}
                            dangerouslySetInnerHTML={{ __html: item.content }}
                          ></div>
                        </div>
                      </Menu.Item>
                    );
                  })}
                </Menu>
              </Sider>
              {this.isEditorShow()}
              {/*<Editor bookContent={this.state.bookContent}></Editor>*/}
              {/*<Editor></Editor>*/}
            </Content>
          </Layout>
        </Layout>
        <Modal
          title="新建笔记"
          visible={this.state.bjvisible}
          onOk={this.notehandleOk.bind(this)}
          onCancel={this.noteHandleCancel.bind(this)}
          cancelText="取消"
          okText="确认"
          bodyStyle={{ zIndex: 100000 }}
        >
          <div style={{ display: "flex", justifyContent: "spaceAround" }}>
            <span style={{ marginRight: "10px" }}>笔记名称:</span>
            <input
              type="text"
              value={this.state.notevalueInput}
              onChange={(e) => {
                this.setState({ notevalueInput: e.target.value });
              }}
              style={{ width: "80%" }}
            />
          </div>
        </Modal>
        {/*重命名对话框*/}
        <Modal
          title="重命名文件夹"
          visible={this.state.reNameFolderVisible}
          onOk={this.reNameHandleOk.bind(this)}
          onCancel={this.reNameHandleCancel.bind(this)}
          cancelText="取消"
          okText="确认"
          bodyStyle={{ zIndex: 100000 }}
        >
          <div style={{ display: "flex", justifyContent: "spaceAround" }}>
            <span style={{ marginRight: "10px" }}>文件夹名称:</span>
            <input
              type="text"
              value={this.state.reNameValueInput}
              onChange={(e) => {
                this.setState({ reNameValueInput: e.target.value });
              }}
              style={{ width: "80%" }}
            />
          </div>
        </Modal>
      </Layout>
    );
  }
}

// const stateToNotebookInfo = (state)=>{
//     return {
//         // state.notebookInfo :notebookInfo
//         notebookInfo:state.notebookInfo
//     }
// }

export default withRouter(Main);
